import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
// 引入路由
import router from './routers/index'
// 引入UI
import Vant from 'vant'
// 引入UI样式
import 'vant/lib/index.css';
// 引入cookies
import VueCookies from 'vue3-cookies'
// 引入接口
import Api from './api/index.js';

let app = createApp(App)
.use(router)
.use(Vant)
.use(VueCookies)
.use(Api)
.mount('#app')

// 路由守卫
router.beforeEach(async(to, from, next) =>{
    //获取meta信息,判断如果为true就是需要登录，false不需要登录
    let IsLogin  = to.meta.auth ? to.meta.auth : false;
    
    // 判断需要用户登陆
    if(IsLogin)
    {
        // 先去获取cookie
        let LoginUser = app.$cookies.get('LoginUser') ? app.$cookies.get('LoginUser') : {}

        if(JSON.stringify(LoginUser) == '{}')
        {
            error('未登陆，请先去登陆');
            // 跳转到登陆页面
            next('/business/login');
            return false;
        }

        //获取用户id
        let busid = LoginUser.id ?? 0;
        let mobile = LoginUser.mobile ??  '';

        let result = await app.$api.check({
            busid: busid,
            mobile: mobile
        });

        if(result.code == 0)
        {
            app.$cookies.remove("LoginUser");
            error('未登陆，请先去登陆');
            // 跳转到登陆页面
            next('/business/login');
            return false;
        }
        else
        {
            app.$cookies.set('LoginUser', result.data)
            next()
        }
    }
    else
    {
        next();
    }
})
